<?php

namespace app\shop\model;
use app\api\service\WechatService;
use app\common\facade\Token;
use app\common\model\Account;
use app\common\model\BaseModel;
use app\common\model\User;
use think\Db;
use think\facade\Log;

class ShopOrder extends BaseModel
{
    public function good(){
        return $this->hasMany('ShopOrderGoods','order_id');
    }
    public function getAddressInfoAttr($val){
        return json_decode($val,true);
    }
    public function goodsRecord(){
        return $this->hasMany('ShopOrderGoods','order_id');
    }
    public function express(){
        return $this->hasOne('ShopOrderExpress','order_id');
    }
    public function sepllOrder(){
        return $this->hasMany(ShopOrder::class,'pt_id','pt_id');
    }
    public function spell(){
        return $this->belongsTo(ShopSpell::class,'pt_id');
    }
    /**
     * 订单支付
     * @Author: rocky
     * 2019/12/11 18:22
     * @param $type 1微信支付，2余额支付
     * @param $order_no 订单号
     * @param $pay_money 支付金额
     * @param $transaction_id 微信流水号
     * @param $password 支付密码
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function pay($type,$order_no,$pay_money,$transaction_id='',$password =''){
        $order = self::where('status', 1)->where('order_no', $order_no)->find();
        if($order){
            Db::startTrans();
            try {
                if($order['type'] == 4){
                    $pt = ShopSpell::find($order['pt_id']);
                    if($pt['status'] == 0 && $order['uid'] == $pt['uid']){
                        //团长将拼团设置拼团中
                         $pt->join_num = 1;
                         $pt->status = 1;
                         $pt->save();
                    }elseif ($pt['status'] == 1){
                        //如果拼团满了，退款
                        if($pt['join_num'] >= $pt['num']){
                            if($type == 1){
                                $res = WechatService::refund($transaction_id,$order_no,$order['total_price'],$pay_money);
                                if($res){
                                    Account::record($pay_money,$order['uid'],"拼团失败 - 支付订单[{$order['title']}]",2,0,"退款至微信钱包 - 订单号：{$order['order_no']}");
                                    Db::commit();
                                }
                                return false;
                            }elseif ($type == 2){
                                //钱包支付直接回滚不操作
                                Db::rollback();
                                return '拼团失败，拼团已满！';
                            }
                        }
                         //拼团加一人
                         $pt->setInc('join_num',1);
                         //拼团成功
                         if($pt['join_num'] == $pt['num']){
                             $pt->status = 2;
                             $pt->save();
                         }
                    }
                }
                if($order['express_type'] ==1){
                    $order->status = 2;
                }elseif ($order['express_type'] ==2){
                    $order->status = 3;
                }
                $order->is_pay = 1;
                $order->pay_time = date('Y-m-d H:i:s');
                $order->pay_price = $pay_money;
                $order->pay_no = $transaction_id;
                $order->save();
                if($type == 1){
                    Account::record($pay_money, $order['uid'],"微信在线支付 - 订单[{$order['title']}]",1,0,"微信在线支付 - 订单号：{$order['order_no']}");
                }elseif($type == 2){
                    $user = Token::user(true);
                    if(empty($password) || $user['pay_pwd'] != md5($password)){
                        return '支付密码错误';
                    }
                    if($user['money'] < $pay_money){
                        return '余额不足';
                    }
                    Account::recordMoney($pay_money,$order['uid'],"钱包支付 - 订单[{$order['title']}]",1,"钱包支付 - 订单号：{$order['order_no']}");
                }
                Db::commit();
                return true;
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('支付错误：'.$e->getMessage());
                return $e->getMessage();
            }
        }else{
            return '订单不允许支付或已支付';
        }
    }
}
